package com.wd.live.module_live.view.activity

import android.annotation.SuppressLint
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ThreadUtils
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.wd.live.module_base.net.bean.live.FindFansInteractListBean
import com.wd.live.module_base.ui.base.BaseActivity
import com.wd.live.module_live.R
import com.wd.live.module_live.databinding.ActivityLiveBinding
import com.wd.live.module_live.view.adapter.FindFansInteractListAdapter
import com.wd.live.module_live.viewmodel.LiveViewModel
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas


@Route(path = "/live/live_activity")
class LiveActivity : BaseActivity<LiveViewModel,ActivityLiveBinding>() {
    private var mRtcEngine: RtcEngine? = null

    private fun initializeAndJoinChannel() {
        try {
            // 创建 RtcEngineConfig 对象，并进行配置
            val config = RtcEngineConfig()
            config.mContext = baseContext
            config.mAppId = "e394d3be4df34e1d9f8b67bc5a007de7"
            config.mEventHandler = object : IRtcEngineEventHandler() {
                // 监听频道内的远端用户，获取用户的 uid 信息
                override fun onUserJoined(uid: Int, elapsed: Int) {
                    runOnUiThread { // 获取 uid 后，设置远端视频视图
                        Log.e("====okhttp 监听频道内的远端用户1", "${uid}")
                        setupRemoteVideo(uid)
                    }
                }
                //加入成功回调
                override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
                    super.onJoinChannelSuccess(channel, uid, elapsed)
                    //推流
                    viewModel.putStartPushStream(viewModel.liveId)
                    Log.e("====okhttp推流","000")
                }

                // 远端用户或主播离开当前频道回调
                override fun onUserOffline(uid: Int, reason: Int) {
                    super.onUserOffline(uid, reason)
                    ThreadUtils.runOnUiThread {
                        Toast.makeText(
                            this@LiveActivity,
                            "User offline: $uid",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
            // 创建并初始化 RtcEngine
            mRtcEngine = RtcEngine.create(config)
        } catch (e: Exception) {
            throw RuntimeException("Check the error.")
        }
        // 启用视频模块
        mRtcEngine?.enableVideo()
        // 开启本地预览
        mRtcEngine?.startPreview()

        // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象
        val container = findViewById<FrameLayout>(com.wd.live.module_live.R.id.local_video_view_container2)
        val surfaceView = SurfaceView(baseContext)
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
        mRtcEngine?.setupLocalVideo(
            VideoCanvas(
                surfaceView,
                VideoCanvas.RENDER_MODE_FIT,
                0
            )
        )
        // 创建 ChannelMediaOptions 对象，并进行配置
        val options = ChannelMediaOptions()
        // 根据场景将用户角色设置为 BROADCASTER (主播) 或 AUDIENCE (观众)
        options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER
        // 直播场景下，设置频道场景为 BROADCASTING (直播场景)
        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING
        // 使用临时 Token 加入频道，自行指定用户 ID 并确保其在频道内的唯一性
        mRtcEngine?.joinChannel(
            "<#Your Token#>", "<#Your channel name#>", 0,
            options
        )
    }

    //设置视图
    private fun setupRemoteVideo(uid: Int) {
        val container = findViewById<FrameLayout>(R.id.remote_video_view_container2)
        val surfaceView = SurfaceView(baseContext)
        surfaceView.setZOrderMediaOverlay(true)
//        container.removeAllViews()
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
        mRtcEngine!!.setupRemoteVideo(
            VideoCanvas(
                surfaceView,
                VideoCanvas.RENDER_MODE_FIT,
                uid
            )
        )
        Log.e("====okhttp 设置远端视图2", "${uid}")
    }
    override fun getLayout(): Int {
        return R.layout.activity_live
    }
    var flag:Boolean=false
    var labsArr= mutableListOf<FindFansInteractListBean>()
    @SuppressLint("SuspiciousIndentation")
    override fun initData() {
        val intExtra = intent.getIntExtra("liveId", 0)
        Log.i("TAGiii", "initData: "+viewModel.liveId+intExtra)


        initializeAndJoinChannel()
        //关闭直播
        binding.deleteLiveActivityId.setOnClickListener(View.OnClickListener {
            viewModel.deleteCloseLive()
        })
        viewModel.dataCloseLive.observe(this){
            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
        }
//        live_play_lm_btn_id
        //连麦
        binding.livePlayLmBtnId.setOnClickListener(View.OnClickListener {
            if (flag){
                flag=false
                binding.constraintLianmai.visibility=View.GONE
                binding.constraintLianmaiYaoqing.visibility=View.GONE
            }else{
                flag=true
                binding.constraintLianmai.visibility=View.VISIBLE
            }
        })
        binding.liveReceiveInvitationId.setOnClickListener(View.OnClickListener {
            //请求网络数据
            viewModel.getFindFansInteractList(intExtra)
            binding.constraintLianmai.visibility=View.GONE
            binding.constraintLianmaiYaoqing.visibility=View.VISIBLE
            binding.lianText2.text="收到连麦邀请"
            binding.lianTime.visibility=View.VISIBLE
            //列表隐藏
            if (labsArr.size!=0){
                binding.lianListLiveId.visibility=View.VISIBLE
                binding.liveWu.visibility=View.GONE
            }else{
                binding.lianListLiveId.visibility=View.GONE
                binding.liveWu.visibility=View.VISIBLE
            }
        })
        binding.liveInviteFriendsId.setOnClickListener(View.OnClickListener {
            binding.constraintLianmai.visibility=View.GONE
            binding.constraintLianmaiYaoqing.visibility=View.VISIBLE
            binding.lianText2.text="邀请好友连麦"
            binding.lianTime.visibility=View.GONE
            //列表隐藏
            binding.lianListLiveId.visibility=View.GONE
            binding.liveWu.visibility=View.VISIBLE
        })

//        收到连麦邀请
        viewModel.dataFindFansInteractList.observe(this){
            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
            binding.constraintLianmai.visibility=View.VISIBLE
            it.result.let {
                it1->
                if (it1 != null) {
                    labsArr.addAll(it1)
                    binding.lianListLiveId.adapter=FindFansInteractListAdapter(this,R.layout.findfansinteractlist_item,labsArr)
                    val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
                    binding.lianListLiveId.layoutManager=linearLayoutManager
                }
            }
                }


        //搭鹊桥

        binding.livePlayMagpieBtnId.setOnClickListener(View.OnClickListener {
         val view = LayoutInflater.from(this).inflate(R.layout.que_item, null)
        val view2 = LayoutInflater.from(this).inflate(R.layout.que_close_item, null)
            if (flag2){
                //搭鹊桥
                showPopupWindow(view)
            }else{
                showPopupWindow(view2)
            }
        })
        //加载布局

    }

    var flag2 :Boolean=true
    fun showPopupWindow(view:View){
        //获取PopupWindow对象 设置宽度为match为 高度自适应
        val popWnd: PopupWindow = PopupWindow(view,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,true)
        popWnd.setContentView(view)
        val sum = view.findViewById<ConstraintLayout>(R.id.que_sum)
        //设置位置
        popWnd.showAtLocation(sum, Gravity.BOTTOM, 0,0)
        popWnd.isFocusable=false
        //为true是开启鹊桥
        if (flag2){
            //取消
            val photograph = view.findViewById<TextView>(R.id.close_que_id)
            photograph.setOnClickListener(View.OnClickListener {
                popWnd.dismiss()
            })
            //确认
            val album_replace = view.findViewById<TextView>(R.id.queren_que_id)
            album_replace.setOnClickListener(View.OnClickListener {
                //动画
                startVideo()
                //设置按钮状态
                flag2=false
                //显示动画
                binding.livePlayMagpieImgId.visibility=View.VISIBLE
                //鹊桥按钮改变动画
                binding.livePlayMagpieBtnId.setBackgroundResource(R.mipmap.live_close_magpie_bridge)
                //关闭弹窗
                popWnd.dismiss()
            })
        }else{
            //关闭鹊桥
            //取消
            val photograph = view.findViewById<TextView>(R.id.close_que_id2)
            photograph.setOnClickListener(View.OnClickListener {
                popWnd.dismiss()
            })

            //确认
            val album_replace = view.findViewById<TextView>(R.id.queren_que_id2)
            album_replace.setOnClickListener(View.OnClickListener {
                flag2=true
                binding.livePlayMagpieImgId.visibility=View.GONE
                binding.livePlayMagpieBtnId.setBackgroundResource(R.mipmap.live_magpie_bridge)
                binding.livePlayMagpieSvgaId.stopAnimation()
                popWnd.dismiss()
            })
        }
    }
    @SuppressLint("SuspiciousIndentation")
    fun startVideo(){

        SVGAParser(this).decodeFromAssets("gesture_guide.svga", object :
            SVGAParser.ParseCompletion {
            @RequiresApi(api = Build.VERSION_CODES.P)
            override fun onComplete(videoItem: SVGAVideoEntity) {
                if ( binding.livePlayMagpieSvgaId != null) {
                    binding.livePlayMagpieSvgaId.setVideoItem(videoItem)
                    binding.livePlayMagpieSvgaId.stepToFrame(0, true)
                }
            }

            override fun onError() {

            }
        })

        binding.livePlayMagpieSvgaId.loops = 100 // 设置动画循环次数，-1表示无限循环
        val parser = SVGAParser.shareParser()
            parser.decodeFromAssets("magpie.svga", object : SVGAParser.ParseCompletion {
                override fun onComplete(videoItem: SVGAVideoEntity) {
//                    val dynamicEntity = SVGADynamicEntity()

//                    binding.livePlayMagpieSvgaId.setVideoItem(videoItem, dynamicEntity)
                    val svgaDrawable = SVGADrawable(videoItem)
                    binding.livePlayMagpieSvgaId.setImageDrawable(svgaDrawable)
                    binding.livePlayMagpieSvgaId.startAnimation()
                }

                override fun onError() {
                    Toast.makeText(this@LiveActivity, "SVGA文件加载失败", Toast.LENGTH_SHORT).show()
                }
            })
    }

    override fun getViewModelClass(): Class<LiveViewModel> {
       return LiveViewModel::class.java
    }

}